<?php

/**
 * Description of tour
 * @author Pham Minh Khoi
 * @email: pmkhoi@gmail.com
 * @package:
 **/

class Tour extends MY_Controller {

    function __construct() {
        parent::__construct();

        $this->checkLogin();
        //$this->checkPermission();
        $this->load->model('tour_model', 'tour', true);
        $this->load->model('tcategory_model', 'tcategory', true);
        $this->load->model('country_model', 'country', true);
        $this->load->model('province_model', 'province', true);
        $this->load->model('tour_type_model', 'type', true);
        $this->load->model('tour_files_model', 'file', true);
        $this->load->model('province_tour_model', 'tour_province', true);
        $this->load->helper('form');
        $this->template->set_template('admin');
        $this->buildMenu();
        $this->template->add_js('js/jquery1.6.1.js');
        $this->template->add_js('js/ckeditor/plugins/htmlwriter/plugin.js');
        //$this->template->add_js('js/jquery1.6.1.js', 'embed');
    }

    function index() {
        $this->view();
    }

    function view($id_country = 0) {
        $this->load->library('pagination');
        $page = (int) $this->uri->segment(5);
        //$base_url = $this->base_url . 'admin/product/view/' . $category . '/';
        $base_url = $this->base_url . 'admin/tour/view/' . $id_country . '/';
        $total_rows = $this->tour->countAll($id_country);
        $per_page = NUMBER_RECORD_PER_PRODUCT_PAGE;
        $uri_segment = 5;
        pagination($base_url, $total_rows, $per_page, $uri_segment);

        $data['rows'] = $this->tour->getAll($page, NUMBER_RECORD_PER_PRODUCT_PAGE, $id_country);
        $index = 0;
        foreach ($data['rows'] as &$row) {
            $row['name'] = $row['vi_name'];
            if (file_exists(TOUR_IMAGE_PATH . $row['image']))
                $row['image'] = '<img src="' . base_url() . TOUR_IMAGE_PATH . $row['image'] . '" with="60px" height="60px">';
            $row['check_best_sell'] = $row['best_sell'] == 1 ? "checked" : "";
            $row['check_special'] = $row['special'] == 1 ? "checked" : "";
            $row['check_active'] = $row['active'] == 1 ? "checked" : "";

            if ($index % 2 == 0)
                $row['css_class'] = 'row1';
            else
                $row['$css_class'] = 'row2';
            $index++;
        }

        if ($page > 0 AND count($products) == 0) {
            redirect('admin/tour/view/' . ($page - NUMBER_RECORD_PER_PAGE));
            return;
        }

        $data['base_url'] = base_url();

        //$data['ddlCategory'] = $this->buidDDProductCategoryList('category', $code_category, 'onchange="loadProduct()"');
        $this->template->parse_view('content', 'admin/tour/tour_list', $data);
        $this->template->render();
    }

    function create() {
        $data['id'] = 0;
        $data['code'] = 0;
        $data['vi_name'] = '';
        $data['en_name'] = '';
        $data['vi_summary'] = '';
        $data['en_summary'] = '';
        $data['vi_description'] = '';
        $data['en_description'] = '';
        $data['tour_category_id'] = 0;
        $data['province_id'] = '';
        $data['price'] = '';
        $data['departure'] = '';
        $data['period'] = '';
        $data['friendly_url'] = '';
        $data['position'] =  $this->tour->getMaxPosition() + 1;
        $data['best_sell'] = 0;
        $data['special'] = 0;
        $data['active'] = 1;
        $data['image'] = '';
        $data['images'] = array();
        $data['ddlCategory'] = $this->buidDDTourCategoryList('ddlCategory', '');

        $data['date_add'] = date('Y-m-d H:i:s', time());
        $data['date_upd'] = date('Y-m-d H:i:s', time());

        $countries = $this->country->getAll();
        $data_countries = array();
        for ($i = 0; $i < count($countries); $i++) {
            $data_countries[$countries[$i]['id']] = $countries[$i]['vi_name'];
        }
        $data['ddlCountry'] = form_dropdown('ddlCountry', $data_countries, 1, 'id= "ddlCountry"');

        $provinces = $this->province->getAll(0, 200, 1);
        $data_provinces = array();
        for ($i = 0; $i < count($provinces); $i++) {
            $data_provinces[$provinces[$i]['id']] = $provinces[$i]['vi_name'];
        }
        $data['ddlProvince'] = form_dropdown('ddlProvince', $data_provinces, 1, 'id= "ddlProvince"');
        $provinces = $this->session->userdata('provinces');
        if(!$provinces)
            $provinces = array();
        $data['provinces'] = $provinces;
       
        $types = $this->type->getAll(0, 200, 1);
        $data_types = array();
        for ($i = 0; $i < count($types); $i++) {
            $data_types[$types[$i]['id']] = $types[$i]['vi_name'];
        }
        $data['ddlType'] = form_dropdown('ddlType', $data_types, 1);

        $data['url_friendly'] = '';
        $data['ckBestSell'] = form_checkbox('ckBestSell', '1', $data['best_sell']);
        $data['ckSpecial'] = form_checkbox('ckSpecial', '1', $data['special']);
        $data['ckActive'] = form_checkbox('ckActive', '1', $data['active']);
        $data['error_message'] = '';
        $data['legend_text'] = lang('create_tour');

        $config['toolbar'] = array(
    array( 'Source','-',
          'NewPage','Preview','Templates','-',
          'Cut','Copy','Paste','PasteText','PasteFromWord','-',
          'Undo','Redo','-',
          'Find','Replace','-',
          'SelectAll','RemoveFormat','-',
          'Maximize', 'ShowBlocks'),
    '/',
    array('Bold','Italic','Underline','Strike','-',
          'Subscript','Superscript','-',
          'NumberedList','BulletedList','-',
          'Outdent','Indent','Blockquote','-',
          'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-',
          'Link','Unlink','Anchor','-',
          'Image','Flash','Table','HorizontalRule','SpecialChar'
          ),
    '/',
    array('Format','Font','FontSize','-',
          'TextColor','BGColor')
);
       $config['toolbar'] = array(
	      array( 'Source', '-', 'Bold', 'Italic', 'Underline', 'Strike' ),
	      array( 'Image', 'Link', 'Unlink', 'Anchor' )
	  );
        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
        $data['config'] = $config;
         $data['base_url'] = base_url();
        //$data['txtViDescription'] = $this->ckeditor->editor("txtViDescription", $data['vi_description'], $config) ;
        //$data['txtEnDescription'] = $this->ckeditor->editor("txtEnDescription", $data['en_description'], $config) ;
        //$this->template->parse_view('content', 'admin/product/create_product', $data);

        $this->template->parse_view('content', 'admin/tour/create_tour', $data);
        $this->template->render();
    }

    function edit($id) {
        $data = $this->tour->findByID($id);

        if(empty ($data)){
            redirect('admin/tour');
        }
        
        $data['images'] =  $this->file->getFileByTourId($id, 1);
        $data['ckBestSell'] = form_checkbox('ckBestSell', '1', $data['best_sell']);
        $data['ckSpecial'] = form_checkbox('ckSpecial', '1', $data['special']);
        $data['ckActive'] = form_checkbox('ckActive', '1', $data['active']);
        $data['error_message'] = '';
        $data['legend_text'] = lang('create_tour');



        $data['provinces'] =  $this->tour_province->getNameLocation($data['id']);
        foreach( $data['provinces'] as $k => &$v){
            $v['tid'] = $v['tour_id'];
            $v['pid'] = $v['province_id'];
        }

        
        $data['ddlCategory'] = $this->buidDDTourCategoryList('ddlCategory', $data['tour_category_id']);

        $countries = $this->country->getAll();
        $data_countries = array();
        for ($i = 0; $i < count($countries); $i++) {
            $data_countries[$countries[$i]['id']] = $countries[$i]['vi_name'];
        }
        $province = $this->province->getById($id);
        $data['ddlCountry'] = form_dropdown('ddlCountry', $data_countries, $province['id_country'], 'id= "ddlCountry"');

        $provinces = $this->province->getAll(0, 200, 1);
        $data_provinces = array();
        for ($i = 0; $i < count($provinces); $i++) {
            $data_provinces[$provinces[$i]['id']] = $provinces[$i]['vi_name'];
        }
        $data['ddlProvince'] = form_dropdown('ddlProvince', $data_provinces, $data['province_id'], 'id= "ddlProvince"');
        
        $types = $this->type->getAll(0, 200, 1);
        $data_types = array();
        for ($i = 0; $i < count($types); $i++) {
            $data_types[$types[$i]['id']] = $types[$i]['vi_name'];
        }
        $data['ddlType'] = form_dropdown('ddlType', $data_types, $data['tour_type_id']);

        $data['ckBestSell'] = form_checkbox('ckBestSell', '1', $data['best_sell']);
        $data['ckSpecial'] = form_checkbox('ckSpecial', '1', $data['special']);
        $data['ckActive'] = form_checkbox('ckActive', '1', $data['active']);
        $data['error_message'] = '';
        $data['legend_text'] = lang('create_tour');
        
        $config['toolbar'] = array(
    array( 'Source','-',
          'NewPage','Preview','Templates','-',
          'Cut','Copy','Paste','PasteText','PasteFromWord','-',
          'Undo','Redo','-',
          'Find','Replace','-',
          'SelectAll','RemoveFormat','-',
          'Maximize', 'ShowBlocks'),
    '/',
    array('Bold','Italic','Underline','Strike','-',
          'Subscript','Superscript','-',
          'NumberedList','BulletedList','-',
          'Outdent','Indent','Blockquote','-',
          'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-',
          'Link','Unlink','Anchor','-',
          'Image','Flash','Table','HorizontalRule','SpecialChar'
          ),
    '/',
    array('Format','Font','FontSize','-',
          'TextColor','BGColor')
);

        
        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        //$this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
        $data['config'] = $config;
        $data['base_url'] = base_url();
        //$data['txtViDescription'] = $this->ckeditor->editor("txtViDescription", $data['vi_description'], $config) ;
        //$data['txtEnDescription'] = $this->ckeditor->editor("txtEnDescription", $data['en_description'], $config) ;

        //$this->template->parse_view('content', 'admin/product/create_product', $data);

        $this->template->parse_view('content', 'admin/tour/create_tour', $data);
        $this->template->render();
    }

    function do_upload($tour_id)
    {
        $this->session->unset_userdata('images');
        $uploaddir = TOUR_IMAGE_PATH; //'./uploads/';
        
        $config['file_name'] =  time(). basename($_FILES['uploadfile']['name']); //date('Y-m-d H:i:s', time()).basename($_FILES['uploadfile']['name']);
        $config['upload_path'] = $uploaddir;
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
            //$config['overwrite'] = true;
            $config['max_size'] = 8192; // 8192 kb = 8mb
            //$config['max_width']  = '1024';
            //$config['max_height']  = '768';
            //$config['max_filename'] = 50;
            //$config['encrypt_name'] = true;
            //$config['remove_spaces'] = false;
            $result_upload = $this->uploadFile($config);
            if ($result_upload['error']) {

                //$error_message = $result_upload['message'];
               //echo "error";
               // echo $result_upload['message'];
                $data['error'] = true;
                //$data['cname'] = $info['cname'];
            } else if($result_upload['error'] == false){
                if($tour_id == 0){
                    $images = $this->session->userdata('images');
                  
                    $images[]['vi_file_name'] = $config['file_name'];
                    
                    $this->session->set_userdata('images', $images);
                    $data['error'] = false;
                    $data['filename'] = $config['file_name'];
                    $data['image_id'] = time();
                }
                else{
                   
                    $image = new stdClass();
                    $image->tour_id = $tour_id;
                    $image->vi_file_name = $config['file_name'];
                    $image->en_file_name = $config['file_name'];
                    $image->vi_alias = '';
                    $image->en_alias = '';
                    $image->vi_description = '';
                    $image->en_description = '';
                    $image->position = $this->file->getMaxPosition() + 1;
                    $image->file_type = 1;
                    $image->active = 1;
                    $image->add_date = date('Y-m-d H:i:s', time());
                    $image->upd_date = date('Y-m-d H:i:s', time());

                    $image_id = $this->file->create($image);
                    //$this->session->set_userdata('images', $images);
                    $data['error'] = false;
                    $data['filename'] = $config['file_name'];
                    $data['image_id'] = $image_id;
                }
                
                //echo $config['file_name']; //"success";

            }



            //$data['pname'] = $info['vi_name'];
            //$data['cname'] = $info['cname'];
            echo json_encode($data);
         //   else{
           //    echo $result_upload['message'];
           // }
           //
           // 
       // $uploaddir = 'C:\\wamp\www\\vntsolution\uploads\\';
       /*
        $file = $uploaddir . basename($_FILES['uploadfile']['name']);

        if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
          echo "success";
        } else {
            //echo "error";
            echo  $file;
        }
        */
    }

    function uploadFile($config) {

        $this->load->library('upload', $config);
        $result = array('error' => false);

        if (!$this->upload->do_upload('uploadfile')) {
            $result['message'] = $this->upload->display_errors();
            $result['error'] = true;
        } else {
            $result['upload_data'] = $this->upload->data();
            //print_r($result['upload_data']);
        }

        return $result;
    }

    function add_province($tour_id = 0, $province_id = 0){
        //$tour_id = intval($this->input->post('txtToutID'));
        //$province_id = intval($this->input->post('txtProvinceID'));

        $info = null;
        $data['tour_id'] = $tour_id;
        $data['province_id'] = $province_id;
        $result = array();
        if($tour_id > 0){
            $item = $this->tour_province->getById($tour_id, $province_id);
            if(!empty ($item)){
                $result['error'] = true;
            }
            else{
                $affected_row = $this->tour_province->insert($data);
                if($affected_row){
                    
                    $result['error'] = false;
                    //$info =  $this->province->getById($province_id);
                    //$result['pname'] = $info['vi_name'];
                    //$result['cname'] = $info['cname'];
                }
                else
                    $result['error'] = true;
            }
        }
        else{
            $provinces = $this->session->userdata('provinces');
            if(!empty ($provinces)){
                if(array_key_exists($tour_id+"_"+$province_id, $provinces))
                    $result['error'] = true;
                else{
                    $result['error'] = false;
                    $info =  $this->province->getById($province_id);

                    $provinces[$tour_id+"_"+$province_id]['tid'] = $tour_id;
                    $provinces[$tour_id+"_"+$province_id]['pid'] = $province_id;
                    $provinces[$tour_id+"_"+$province_id]['pname'] = $info['vi_name'];
                    $provinces[$tour_id+"_"+$province_id]['cname'] = $info['cname'];
                    $this->session->set_userdata('provinces', $provinces);
                }
            }
            else{
                $result['error'] = false;
                $info =  $this->province->getById($province_id);
                
                $provinces[$tour_id+"_"+$province_id]['tid'] = $tour_id;
                $provinces[$tour_id+"_"+$province_id]['pid'] = $province_id;
                $provinces[$tour_id+"_"+$province_id]['pname'] = $info['vi_name'];
                $provinces[$tour_id+"_"+$province_id]['cname'] = $info['cname'];
                $this->session->set_userdata('provinces', $provinces);
            }
            
            
        }


        if( $result['error'] == false){
            if(empty($info))
                $info =  $this->province->getById($province_id);
            //$result['error'] = false;
            $result['pname'] = $info['vi_name'];
            $result['cname'] = $info['cname'];
        }
      
       // $affected_row = $this->tour_province->insert($data);
        echo json_encode($result);
    }

    function delete_location(){
        $tour_id = intval($this->input->post('tour_id'));
        $province_id = intval($this->input->post('province_id'));
        $provinces = $this->session->userdata('provinces');
        $result['error'] = true;
        if($tour_id == 0){
            if(array_key_exists($tour_id+"_"+$province_id, $provinces)){
                $result['error'] = false;
                unset ($provinces[$tour_id+"_"+$province_id]);
                $this->session->set_userdata('provinces', $provinces);
            }
        }
        else{
            $affected_row = $this->tour_province->delete($tour_id, $province_id);
            $result['error'] = false;
        }

        echo json_encode($result);
    }
    
    function set_image(){
        $imageName = $this->input->post('image_name');
        $tourID = $this->input->post('tour_id');
        if($tourID > 0){
            $resutl = $this->tour->setImage($imageName, $tourID);
            if($resutl){
                 $result['error'] = false;
            }
             $result['error'] = true;
        }
        else{
            $result['error'] = false;
            $this->session->set_userdata('image_default', $imageName);
        }

         echo json_encode($result);
    }

    function delete_image(){
        $imageName = $this->input->post('image_name');
        $tourID = $this->input->post('tour_id');
        $result['error'] = false;
        
        if($tourID > 0){
            $_resutl = $this->file->deleteByName($imageName);
            
            $tour  = $this->tour->findByID($tourID);
            if(!empty ($tour) ){
                if($tour['image'] == $imageName)
                    $this->tour->setImage('', $tourID);
               
            }
            
            if($_resutl){
                 $result['error'] = false;
            }
            else
             $result['error'] = true;
            

           
        }
        else{
            $result['error'] = false;
            $images = $this->session->userdata('images');
            for($i = 0; $i < count($images); $i++){
                if($images[$i] == $imageName ){
                    unset($images[$i]);
                    $image_default = $this->session->userdata('image_default');
                    if( $image_default == $imageName)
                        $this->session->unset_userdata('image_default');
                    break;
                }
            }
            $this->session->set_userdata('images', $images);
            
        }
        
        @unlink(TOUR_IMAGE_PATH.$imageName);

        echo json_encode($result);
    }

    function buidDDTourCategoryList($name, $default){
        //$this->load->model('pcategory_model', 'category', true);
        $categories = $this->tcategory->getAll(-1);
       // print_r($categories);
        //$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
        $space = '';
        //$name = 'Parent';
        $value = '';
        $selected = '';
        $space= '';
        $label = 'Parent';
        $class = '';
        $action = '';
        $style = '';

        $tmp = array();
        for($i = 0; $i <count($categories); $i++){
            $category = $categories[$i];
            //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
            $tmp[$category->id_parent][$category->id] = $category;
        }

        //$options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($tmp/*$categories*/, '', $default);
        $options = $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true) . $this->getCategoryOption($tmp/* $categories */, '0', $default);
        $data = array();
        $data['name'] = $name;
        $data['style'] = $style;
        $data['class'] = $class;
        $data['action'] = $action;
        $data['options'] = $options;
        return $this->load->view('admin/select', $data, true);
        //return eval($this->loadTemplate('admin/ddl.tpl'));
    }

    function getCategoryOption($tmp/*$categories*/, $parent = 0/*0*/, $default = 0/*0*/, $space = '&nbsp;'){
        $items = '';
        if(isset($tmp[$parent])){
            $num_record = count($tmp[$parent]);
            foreach($tmp[$parent] as $k => $v){
                //$parent = $v->id_pcategory;
                //$value = $v->id_pcategory;
                //echo '<br>\n'.$parent . '_\n';
                $parent = $v->id;
                $value = $v->id;
                $label = $v->vi_name;
                $selected = '';
                if($value == $default) $selected = 'selected';
                $items .= $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true);
                $items .=$this->getCategoryOption($tmp/* $categories */, $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            }
        }

        return $items;
    }

    function save(){
        $txtID = (int) trim($this->input->post('txtID'));
        $txtFriendlyUrl = trim($this->input->post('txtFriendlyURL'));
        $txtCode = trim($this->input->post('txtCode'));
        $data = array();
        
        if ($txtID > 0){
            $tour = $this->tour->findByID($txtID);

            if (empty($tour)) {
                redirect('admin/tour/view');
                return;
            }
            
            $data = $tour;

        }
        else {
            $data['id'] = 0;
            $data['code'] = $txtCode;
            $data['friendly_url'] = $txtFriendlyUrl;
            //$data['image'] = '';
            $images = $this->session->userdata('images');
            if(empty ($images))
                $images = array();
            $data['images'] = $images;
            $image = $this->session->userdata('image_default');
            if(empty ($image))
                $image = '';
            $data['image'] = $image;
            //print_r($images);
        }

      

        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');

        if ((($txtFriendlyUrl != $data['friendly_url'] && $txtID > 0) || $txtID == 0) && $txtFriendlyUrl != '') {
            $this->form_validation->set_rules('txtFriendlyURL', 'lang:friendly_url', 'min_length[2]|max_length[120]|callback_friendly_url_check');
            //echo $txtCode.' '.$category->code; return;
        }

        if ((($txtCode != $data['code'] && $txtID > 0) || $txtID == 0) && $txtCode != '') {
            $this->form_validation->set_rules('txtCode', 'lang:code', 'min_length[2]|max_length[120]|callback_code_check');
            //echo $txtCode.' '.$category->code; return;
        }
        
        $this->form_validation->set_rules('category', 'lang:category', 'callback_select_category_check');
        $this->form_validation->set_message('code_check', '%s is not available.');
        $this->form_validation->set_rules('txtViName', 'lang:vi_name', 'required|min_length[2]|max_length[120]');
        $this->form_validation->set_rules('txtEnName', 'lang:en_name', 'required|min_length[2]|max_length[120]');
        $this->form_validation->set_rules('txtViSummary', 'lang:vi_summary', 'required|min_length[2]|max_length[800]');
        $this->form_validation->set_rules('txtEnSummary', 'lang:en_summary', 'required|min_length[2]|max_length[800]');
        $this->form_validation->set_rules('txtViDescription', 'lang:vi_description', 'required|min_length[2]');
        $this->form_validation->set_rules('txtEnDescription', 'lang:en_description', 'required|min_length[2]');
        $this->form_validation->set_rules('txtDeparture', 'lang:departure', 'required|min_length[2]');
        $this->form_validation->set_rules('txtPeriod', 'lang:period', 'required|min_length[2]');
       
        //if($txtLinkRewrite!='' AND $txtLinkRewrite!=$category->link_rewrite)
        //$this->form_validation->set_rules('txtLinkRewrite', 'lang:friendly_url', 'callback_friendly_url_check');
        /* $this->form_validation->set_rules('password', 'Password', 'required');
          $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
          $this->form_validation->set_rules('email', 'Email', 'required');
         */

        $data['code'] = trim($this->input->post('txtCode'));
        $data['tour_category_id'] = trim($this->input->post('ddlCategory'));
        $data['vi_name'] = trim($this->input->post('txtViName'));
        $data['en_name'] = trim($this->input->post('txtEnName'));
        $data['vi_summary'] = trim($this->input->post('txtViSummary'));
        $data['en_summary'] = trim($this->input->post('txtEnSummary'));
        $data['vi_description'] = trim($this->input->post('txtViDescription'));
        $data['en_description'] = trim($this->input->post('txtEnDescription'));
        $data['position'] = trim($this->input->post('txtPosition'));
        $data['active'] = (int) $this->input->post('active');
        $data['price'] = trim($this->input->post('txtPrice'));
        $data['period'] = trim($this->input->post('txtPeriod'));
        $data['departure'] = trim($this->input->post('txtDeparture'));
        $data['friendly_url'] = trim($this->input->post('txtFriendlyURL'));
        $data['province_id'] = trim($this->input->post('ddlProvince'));
        $data['tour_type_id'] = (int) $this->input->post('ddlType');
        $data['best_sell'] = intval($this->input->post('ckBestSell'));
        $data['special'] = trim($this->input->post('ckSpecial'));
        $data['active'] = trim($this->input->post('ckActive'));
        
        //$data['image'] = '';
        $data['video'] = '';
        $data['visited'] = 0;
        $product->image = '';
        $data['date_add'] = date('Y-m-d H:i:s', time());
        $data['date_upd'] = date('Y-m-d H:i:s', time());

        $error_message = ''; // $this->loadErrorMessage('Thong diep loi.');
        //print_r($_POST);
        $attach_image = false;
        $image_upload = array('error' => false);
        if (isset($_FILES['file']['tmp_name']) AND strlen($_FILES['file']['tmp_name']) > 0) {
            $attach_image = true;
            $image_upload = $this->upload_image('file', NEWS_IMAGE_PATH /* './Data/Images/Product/' */);
            if ($image_upload['error'])
                $error_message .= $image_upload['message'];
        }

        /* if($attach_image == true AND $image_upload['error']==true){
          echo 'Not is image'; return;
          } */

        if ($this->form_validation->run() == FALSE OR ($attach_image == true AND $image_upload['error'] == true)) {

            $error_message = validation_errors() . '<br>' . $error_message;
            //$code = uniqid();
            //$this->session->set_userdata('code', $code);

           // $data = array();
          //  $data['news'] = $news;
       
        $data['ddlCategory'] = $this->buidDDTourCategoryList('ddlCategory', $data['tour_category_id']);
        $data['country_id'] = trim($this->input->post('ddlCountry'));
        $countries = $this->country->getAll();
        $data_countries = array();
        for ($i = 0; $i < count($countries); $i++) {
            $data_countries[$countries[$i]['id']] = $countries[$i]['vi_name'];
        }

        //$province = $this->province->getByID

        $data['ddlCountry'] = form_dropdown('ddlCountry', $data_countries,  $data['country_id'], 'id= "ddlCountry"');

        $provinces = $this->province->getAll(0, 200, 1);
        $data_provinces = array();
        for ($i = 0; $i < count($provinces); $i++) {
            $data_provinces[$provinces[$i]['id']] = $provinces[$i]['vi_name'];
        }
        $data['ddlProvince'] = form_dropdown('ddlProvince', $data_provinces, $data['province_id'], 'id= "ddlProvince"');
        if($txtID > 0){
            $data['provinces'] =  $this->tour_province->getNameLocation($data['id']);
            //if()
            foreach( $data['provinces'] as $k => &$v){
            $v['tid'] = $v['tour_id'];
            $v['pid'] = $v['province_id'];
            }
        }
        else
            $data['provinces'] =  $this->session->userdata('provinces');


        $types = $this->type->getAll(0, 200, 1);
        $data_types = array();
        for ($i = 0; $i < count($types); $i++) {
            $data_types[$types[$i]['id']] = $types[$i]['vi_name'];
        }
        $data['ddlType'] = form_dropdown('ddlType', $data_types, $data['tour_type_id']);
        
        $data['ckBestSell'] = form_checkbox('ckBestSell', '1', $data['best_sell']);
        $data['ckSpecial'] = form_checkbox('ckSpecial', '1', $data['special']);
        $data['ckActive'] = form_checkbox('ckActive', '1', $data['active']);
        
        $data['error_message'] = '<div style="color:red">' . $error_message . '</div>';
        //if()
        $data['legend_text'] = $txtID > 0 ? lang('edit_news') : lang('create_news');

        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');


         $config['toolbar'] = array(
          array( 'Source', '-', 'Bold', 'Italic', 'Underline', 'Strike' ),
          array( 'Image', 'Link', 'Unlink', 'Anchor' )
      );

        $this->load->library('ckeditor');
        $this->load->library('ckFinder');
        $this->template->add_js('asset/ckeditor/ckeditor.js');
        $this->template->add_js('asset/ckfinder/ckfinder.js');
        //configure base path of ckeditor folder
        $this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
        $this->ckeditor->config['toolbar'] = 'Full';
        $this->ckeditor->config['language'] = 'en';
        //configure ckfinder with ckeditor config
        $this->ckfinder->SetupCKEditor($this->ckeditor, 'asset/ckfinder');
        $data['config'] = $config;
         $data['base_url'] = base_url();
            $this->template->parse_view('content', 'admin/tour/create_tour', $data);
            $this->template->render();

            return;
        } else {
            //$this->load->model('pcategory_model', 'pcategory', true);
            //$cat = $this->pcategory->getByCode($product->code_pcategory);
            //$product->id_pcategory = $cat->id_pcategory;
            if ($attach_image) {
                $file_path = $image_upload['upload_data']['file_name'];
                if ($txtID > 0 AND $data['image'] != $file_path) {
                    @unlink(NEWS_IMAGE_PATH.$data['image']);
                }
                
                $data['image'] =  $file_path;
            }

            //$this->load->model('ncategory_model', 'ncategory', true);
           // $tcategory = $this->tcategory->getById($data['id_tour_category']);
            //$data['code_ncategory'] = $ncategory['code'];

            $result = 0;
            
            if ($txtID > 0) {
                $result = $this->tour->update($data);
            } else {

               // $data['date_add'] = date('Y-m-d H:i:s', time());
                $result = $this->tour->create($data);
            }

                       
            $images = $this->session->userdata('images');

            if ($txtID == 0 && $result > 0) {
                if(!empty($images) && count($images) > 0){
       
                $_images = array();
                for ($i = 0; $i < count($images); $i++) {
                    $name_image = $images[$i];
                    $image = new stdClass();
                    $image->tour_id = $result;
                    $image->vi_file_name = $name_image['vi_file_name'];
                    $image->en_file_name = $name_image['vi_file_name'];
                    $image->vi_alias = '';
                    $image->en_alias = '';
                    $image->vi_description = '';
                    $image->en_description = '';
                    $image->position = $this->file->getMaxPosition() + 1;
                    $image->file_type = 1;
                    $image->active = 1;
                    $image->add_date = date('Y-m-d H:i:s', time());
                    $image->upd_date = date('Y-m-d H:i:s', time());

                    $_images[] = $image;
                    

                    }

                if (count($_images) > 0) {
                    
                    $this->file->create($_images);
                    
                }
                $this->session->unset_userdata('images');
                }

                // add location:
                $provinces = $this->session->userdata('provinces');
                if(!empty($provinces) && count($provinces) > 0){
                    foreach($provinces as $k => $v){
                        $v['province_id'] = $v['pid'];
                        $v['tour_id'] = $result;
                        //print_r($v);
                        //$tmp['province_id'] =
                        $this->tour_province->insert($v);
                        
                    }
                    $this->session->unset_userdata('provinces');
                }
            }



            redirect('admin/tour/view');
        }
    }

    function friendly_url_check($url) {
        $result = $this->tour->getByFriendlyUrl($url);
        if ($result != null) {
            $this->form_validation->set_message('friendly_url_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function code_check($code) {
        $result = $this->tour->getByCode($code);
        if ($result != null) {
            $this->form_validation->set_message('code_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

} // end class.

?>
